import * as PIXI from 'pixi.js';
import { GameConfig, defaultConfig } from './config';
import { Player } from './entities/player';
import { VehicleManager } from './managers/vehicleManager';
import { UI } from './ui/ui';

export class Game {
    private app: PIXI.Application;
    private config: GameConfig;
    private gameContainer: PIXI.Container;
    private player: Player;
    private vehicleManager: VehicleManager;
    private ui: UI;
    private isGameStarted: boolean = false;
    private isLevelCompleted: boolean = false;
    private currentLevel: number = 1;
    private isMobile: boolean;
    private gyroscopeAvailable: boolean = false;
    private keyPressed: { [key: string]: boolean } = {};

    constructor(app: PIXI.Application, config: GameConfig = defaultConfig) {
        this.app = app;
        this.config = config;
        
        // 检测是否为移动设备
        this.isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        // 创建游戏容器
        this.gameContainer = new PIXI.Container();
        this.app.stage.addChild(this.gameContainer);
        
        // 创建背景
        const background = this.createBackground();
        
        // 初始化游戏组件
        this.player = new Player(this.config);
        this.vehicleManager = new VehicleManager(this.config);
        this.ui = new UI(this.config, this.app);
        
        // 按照层次添加组件
        this.gameContainer.addChild(background);          // 底层：背景
        this.gameContainer.addChild(this.vehicleManager.container);  // 中层：车辆
        this.gameContainer.addChild(this.player.container);  // 上层：玩家
        this.app.stage.addChild(this.ui.container);      // UI层
        
        // 设置事件监听
        this.setupEventListeners();
    }

    private createBackground(): PIXI.Container {
        const container = new PIXI.Container();
        
        // 1. 创建背景层
        const background = new PIXI.Graphics();
        background.beginFill(0x2ecc71);  // 绿色草地背景
        background.drawRect(0, 0, this.config.screenWidth, this.config.screenHeight);
        background.endFill();
        
        // 添加草地纹理
        const addGrassTexture = () => {
            background.lineStyle(0);
            for (let i = 0; i < 300; i++) {
                const x = Math.random() * this.config.screenWidth;
                const y = Math.random() * this.config.screenHeight;
                
                // 不在马路区域添加草
                if (x > this.config.roadOffset && x < this.config.screenWidth - this.config.roadOffset) {
                    continue;
                }
                
                const size = Math.random() * 4 + 2;
                background.beginFill(0x27ae60, 0.3);  // 深绿色，半透明
                background.drawCircle(x, y, size);
                background.endFill();
            }
        };
        
        // 添加装饰性树木
        const addTrees = () => {
            const treePositions = [
                { x: this.config.roadOffset / 2, y: this.config.screenHeight * 0.2 },
                { x: this.config.roadOffset / 2, y: this.config.screenHeight * 0.6 },
                { x: this.config.screenWidth - this.config.roadOffset / 2, y: this.config.screenHeight * 0.3 },
                { x: this.config.screenWidth - this.config.roadOffset / 2, y: this.config.screenHeight * 0.7 }
            ];
            
            treePositions.forEach(pos => {
                // 树干
                background.beginFill(0x795548);
                background.drawRect(pos.x - 5, pos.y, 10, 40);
                background.endFill();
                
                // 树冠
                background.beginFill(0x27ae60);
                background.drawCircle(pos.x, pos.y - 10, 20);
                background.endFill();
            });
        };
        
        addGrassTexture();
        addTrees();
        
        // 2. 创建马路层
        const roadLayer = new PIXI.Graphics();
        
        // 绘制马路
        roadLayer.beginFill(0x95a5a6);  // 浅灰色
        roadLayer.drawRect(
            this.config.roadOffset, 
            0, 
            this.config.screenWidth - 2 * this.config.roadOffset, 
            this.config.screenHeight
        );
        roadLayer.endFill();

        // 添加路面纹理
        const addRoadTexture = () => {
            roadLayer.lineStyle(0);
            const roadWidth = this.config.screenWidth - 2 * this.config.roadOffset;
            for (let i = 0; i < 500; i++) {
                const x = this.config.roadOffset + Math.random() * roadWidth;
                const y = Math.random() * this.config.screenHeight;
                const size = Math.random() * 2 + 1;
                const alpha = Math.random() * 0.05;
                
                roadLayer.beginFill(0x7f8c8d, alpha);
                roadLayer.drawCircle(x, y, size);
                roadLayer.endFill();
            }
        };

        // 绘制车道线
        const drawLaneLines = () => {
            const laneWidth = (this.config.screenWidth - 2 * this.config.roadOffset) / this.config.laneCount;
            
            // 车道分隔线
            for (let i = 1; i < this.config.laneCount; i++) {
                const x = this.config.roadOffset + i * laneWidth;
                // 虚线
                roadLayer.lineStyle(2, 0xffffff, 0.3);
                for (let y = 0; y < this.config.screenHeight; y += 30) {
                    roadLayer.moveTo(x, y);
                    roadLayer.lineTo(x, y + 15);
                }
            }
        };

        // 应用纹理和车道线
        addRoadTexture();
        drawLaneLines();
        
        // 3. 创建天桥层
        const bridgeLayer = new PIXI.Graphics();
        
        // 天桥的影子（半透明深色）
        bridgeLayer.beginFill(0x2c3e50, 0.3);
        bridgeLayer.lineStyle(0);
        
        // 桥面的影子
        const shadowY = this.config.bridge.y - 100;
        bridgeLayer.drawRect(
            this.config.bridge.leftX,
            shadowY,
            this.config.bridge.width,
            20
        );
        
        // 支柱的影子（略微倾斜）
        const pillarShadowWidth = 15;
        const shadowSkew = 10;
        
        // 左支柱影子
        const leftPillarX = this.config.bridge.leftX + this.config.bridge.platformWidth;
        bridgeLayer.moveTo(leftPillarX - pillarShadowWidth/2 + shadowSkew, shadowY);
        bridgeLayer.lineTo(leftPillarX + pillarShadowWidth/2 + shadowSkew, shadowY);
        bridgeLayer.lineTo(leftPillarX + pillarShadowWidth/2, shadowY + 100);
        bridgeLayer.lineTo(leftPillarX - pillarShadowWidth/2, shadowY + 100);
        bridgeLayer.closePath();
        
        // 右支柱影子
        const rightPillarX = this.config.bridge.rightX - this.config.bridge.platformWidth;
        bridgeLayer.moveTo(rightPillarX - pillarShadowWidth/2 + shadowSkew, shadowY);
        bridgeLayer.lineTo(rightPillarX + pillarShadowWidth/2 + shadowSkew, shadowY);
        bridgeLayer.lineTo(rightPillarX + pillarShadowWidth/2, shadowY + 100);
        bridgeLayer.lineTo(rightPillarX - pillarShadowWidth/2, shadowY + 100);
        bridgeLayer.closePath();
        
        bridgeLayer.endFill();
        
        // 桥面
        bridgeLayer.beginFill(0x7f8c8d);
        bridgeLayer.lineStyle(2, 0x6c7a7a);
        bridgeLayer.drawRect(
            this.config.bridge.leftX,
            this.config.bridge.y,
            this.config.bridge.width,
            this.config.bridge.height
        );
        bridgeLayer.endFill();
        
        // 两侧站台（起点和终点）
        // 左侧站台（起点）
        bridgeLayer.beginFill(0x2ecc71);  // 绿色，��示起点
        bridgeLayer.drawRect(
            this.config.bridge.leftX,
            this.config.bridge.y,
            this.config.bridge.platformWidth,
            this.config.bridge.height
        );
        
        // 右侧站台（终点）
        bridgeLayer.beginFill(0xe74c3c, 0.5);  // 红色（半透明），表示终点站台
        bridgeLayer.drawRect(
            this.config.bridge.rightX - this.config.bridge.platformWidth,
            this.config.bridge.y,
            this.config.bridge.platformWidth,
            this.config.bridge.height
        );
        bridgeLayer.endFill();

        // 终点检查区域标记（明显的红色区域）
        bridgeLayer.beginFill(0xff0000, 0.8);  // 鲜红色
        bridgeLayer.lineStyle(2, 0xffffff);    // 白色边框
        bridgeLayer.drawRect(
            this.config.bridge.rightX - this.config.bridge.platformWidth - this.config.bridge.goalTriggerWidth,
            this.config.bridge.y - 5,  // 稍微高一点，让标记更明显
            this.config.bridge.goalTriggerWidth,
            this.config.bridge.height + 10
        );
        bridgeLayer.endFill();

        // 添加终点标记箭头
        const arrowHeight = 20;
        const arrowWidth = 15;
        bridgeLayer.beginFill(0xff0000);
        bridgeLayer.lineStyle(2, 0xffffff);
        // 绘制向下的箭头
        bridgeLayer.moveTo(
            this.config.bridge.rightX - this.config.bridge.platformWidth - this.config.bridge.goalTriggerWidth / 2,
            this.config.bridge.y - 25
        );
        bridgeLayer.lineTo(
            this.config.bridge.rightX - this.config.bridge.platformWidth - this.config.bridge.goalTriggerWidth / 2 - arrowWidth,
            this.config.bridge.y - 25 - arrowHeight
        );
        bridgeLayer.lineTo(
            this.config.bridge.rightX - this.config.bridge.platformWidth - this.config.bridge.goalTriggerWidth / 2 + arrowWidth,
            this.config.bridge.y - 25 - arrowHeight
        );
        bridgeLayer.closePath();
        bridgeLayer.endFill();
        
        // 桥的支柱
        const pillarWidth = 20;
        const pillarHeight = 80;
        const pillarY = this.config.bridge.y + this.config.bridge.height;
        
        bridgeLayer.beginFill(0x7f8c8d);
        // 左支柱
        bridgeLayer.drawRect(leftPillarX - pillarWidth/2, pillarY, pillarWidth, pillarHeight);
        // 右支柱
        bridgeLayer.drawRect(rightPillarX - pillarWidth/2, pillarY, pillarWidth, pillarHeight);
        bridgeLayer.endFill();
        
        // 栏杆
        const railingHeight = 15;
        bridgeLayer.beginFill(0x95a5a6);
        bridgeLayer.lineStyle(1, 0x6c7a7a);
        
        // 栏杆立柱
        const postSpacing = 30;
        const postWidth = 4;
        for (let x = this.config.bridge.leftX; x <= this.config.bridge.rightX; x += postSpacing) {
            bridgeLayer.drawRect(x, this.config.bridge.y - railingHeight, postWidth, railingHeight);
            bridgeLayer.drawRect(x, this.config.bridge.y + this.config.bridge.height - railingHeight, 
                               postWidth, railingHeight);
        }
        
        // 栏杆横杆
        bridgeLayer.lineStyle(2, 0x95a5a6);
        bridgeLayer.moveTo(this.config.bridge.leftX, this.config.bridge.y - railingHeight * 0.7);
        bridgeLayer.lineTo(this.config.bridge.rightX, this.config.bridge.y - railingHeight * 0.7);
        bridgeLayer.moveTo(this.config.bridge.leftX, this.config.bridge.y + this.config.bridge.height - railingHeight * 0.3);
        bridgeLayer.lineTo(this.config.bridge.rightX, this.config.bridge.y + this.config.bridge.height - railingHeight * 0.3);

        // 添加起点和终点文字
        const textStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 20,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 4,
            align: 'center'
        });

        // 起点文字
        const startText = new PIXI.Text('START', textStyle);
        startText.anchor.set(0.5);
        startText.x = this.config.bridge.leftX + this.config.bridge.platformWidth / 2;
        startText.y = this.config.bridge.y + this.config.bridge.height / 2;
        startText.rotation = -Math.PI / 2;  // 垂直旋转

        // 终点文字
        const endText = new PIXI.Text('GOAL', textStyle);
        endText.anchor.set(0.5);
        endText.x = this.config.bridge.rightX - this.config.bridge.platformWidth / 2;
        endText.y = this.config.bridge.y + this.config.bridge.height / 2;
        endText.rotation = -Math.PI / 2;  // 垂直旋转

        // 添加箭头指示
        const arrowStyle = new PIXI.TextStyle({
            fontFamily: 'Arial',
            fontSize: 24,
            fontWeight: 'bold',
            fill: '#ffffff',
            stroke: '#000000',
            strokeThickness: 4
        });

        // 起点箭头（向右）
        const startArrow = new PIXI.Text('→', arrowStyle);
        startArrow.anchor.set(0.5);
        startArrow.x = this.config.bridge.leftX + this.config.bridge.platformWidth - 10;
        startArrow.y = this.config.bridge.y + this.config.bridge.height / 2;

        // 终点箭头（向左）
        const endArrow = new PIXI.Text('←', arrowStyle);
        endArrow.anchor.set(0.5);
        endArrow.x = this.config.bridge.rightX - this.config.bridge.platformWidth + 10;
        endArrow.y = this.config.bridge.y + this.config.bridge.height / 2;

        // 按层次添加到容器
        container.addChild(background);  // 最底层：背景
        container.addChild(roadLayer);   // 中层：马路
        container.addChild(bridgeLayer); // 上层：天桥
        container.addChild(startText);   // 起点文字
        container.addChild(endText);     // 终点文字
        container.addChild(startArrow);  // 起点箭头
        container.addChild(endArrow);    // 终点箭头
        
        return container;
    }

    private setupEventListeners(): void {
        // 键盘控制
        window.addEventListener('keydown', (e: KeyboardEvent) => {
            this.keyPressed[e.key] = true;
        });
        
        window.addEventListener('keyup', (e: KeyboardEvent) => {
            this.keyPressed[e.key] = false;
        });
        
        // 触摸控制
        if (this.isMobile) {
            this.app.view.addEventListener('pointerdown', this.handlePointerDown.bind(this));
            this.app.view.addEventListener('pointermove', this.handlePointerMove.bind(this));
            this.app.view.addEventListener('pointerup', this.handlePointerUp.bind(this));
            this.app.view.addEventListener('pointerout', this.handlePointerUp.bind(this));
            
            // 检查陀螺仪是否可用
            if (window.DeviceOrientationEvent) {
                window.addEventListener('deviceorientation', this.handleDeviceOrientation.bind(this));
                this.gyroscopeAvailable = true;
            }
        }
        
        // 游戏循环
        this.app.ticker.add(this.gameLoop.bind(this));
    }

    private handlePointerDown(e: PointerEvent): void {
        if (!this.isGameStarted) return;
        
        const rect = (e.target as HTMLCanvasElement).getBoundingClientRect();
        const x = e.clientX - rect.left;
        const normalizedX = x / rect.width;
        
        // 根据触摸位置决定移动方向
        if (normalizedX < 0.5) {
            this.player.moveLeft();
        } else {
            this.player.moveRight();
        }
    }

    private handlePointerMove(e: PointerEvent): void {
        if (!this.isGameStarted) return;
        
        const rect = (e.target as HTMLCanvasElement).getBoundingClientRect();
        const x = e.clientX - rect.left;
        const normalizedX = x / rect.width;
        
        // 根据触摸位置决定移动方向
        if (normalizedX < 0.5) {
            this.player.moveLeft();
        } else {
            this.player.moveRight();
        }
    }

    private handlePointerUp(): void {
        if (!this.isGameStarted) return;
        this.player.stop();
    }

    private handleDeviceOrientation(e: DeviceOrientationEvent): void {
        if (!this.isGameStarted || !this.gyroscopeAvailable) return;
        
        const gamma = e.gamma; // 左右倾斜角度 [-90, 90]
        if (gamma === null) return;
        
        const threshold = 10; // 倾斜角度阈值
        
        if (gamma < -threshold) {
            this.player.moveLeft();
        } else if (gamma > threshold) {
            this.player.moveRight();
        } else {
            this.player.stop();
        }
    }

    private gameLoop(delta: number): void {
        if (!this.isGameStarted) return;
        
        // 获取当前速度
        const currentSpeed = this.vehicleManager.getCurrentSpeed(this.config.speed.initial);
        
        // 更新游戏组件
        this.player.update(delta);
        this.vehicleManager.update(delta, currentSpeed);
        
        // 检测碰撞
        if (this.checkCollisions()) {
            this.handleGameOver();
            return;
        }
        
        // 检查是否到达终点
        if (!this.isLevelCompleted) {
            const playerBounds = this.player.getCharacterBounds();
            // 终点检测位置（更靠近终点站台）
            const goalX = this.config.bridge.rightX - this.config.bridge.platformWidth - this.config.bridge.goalTriggerWidth / 2;
            
            if (playerBounds.x + playerBounds.width > goalX) {
                this.handleLevelComplete();
                return;
            }
        }
        
        // 更新UI
        this.ui.updateSpeed(this.vehicleManager.getSpeedInKmh());
        
        // 处理键盘输入
        this.handleKeyboardInput();
    }

    private handleKeyboardInput(): void {
        // 左右移动
        if (this.keyPressed['ArrowLeft'] || this.keyPressed['a'] || this.keyPressed['A']) {
            this.player.moveLeft();
        } else if (this.keyPressed['ArrowRight'] || this.keyPressed['d'] || this.keyPressed['D']) {
            this.player.moveRight();
        } else if (!this.isMobile || !this.gyroscopeAvailable) {
            this.player.stop();
        }
    }

    private checkCollisions(): boolean {
        const result = this.vehicleManager.checkCollisionWithShadow(this.player.getShadowBounds());
        if (result.collided && result.point) {
            this.player.showCollisionEffect(result.point);
        }
        return result.collided;
    }

    private handleGameOver(): void {
        this.isGameStarted = false;
        
        // 显示游戏结束界面
        this.ui.showGameOver(this.currentLevel, {
            onContinue: () => {
                // 继续当前关卡
                this.continueGame();
            },
            onRestart: () => {
                // 从第一关重新开始
                this.currentLevel = 1;
                this.startGame();
            }
        });
    }

    private handleLevelComplete(): void {
        if (this.isLevelCompleted) return;  // 防止重复触发
        
        this.isLevelCompleted = true;
        this.isGameStarted = false;
        
        // 播放过关动效
        this.player.playVictoryAnimation(() => {
            // 动效播放完成后显示关卡完成界面
            this.ui.showLevelComplete(this.currentLevel, {
                onContinue: () => {
                    // 进入下一关
                    this.currentLevel++;
                    this.isLevelCompleted = false;
                    this.player.reset();
                    this.vehicleManager.increaseSpeed();  // 增加车速，提高难度
                    this.startGame();
                }
            });
        });
    }

    private continueGame(): void {
        this.player.reset();
        this.startGame();
    }

    public startGame(): void {
        // 重置游戏状态
        this.isGameStarted = false;
        this.player.reset();
        this.vehicleManager.reset();
        
        // 更新UI显示
        this.ui.updateLevel(this.currentLevel);
        
        // 显示关卡开始
        this.ui.showLevelStart(this.currentLevel, () => {
            this.isGameStarted = true;
            this.vehicleManager.start(this.currentLevel);
        });
    }
}